package com.yundasys.lab04springbootlocalmsg.consumer;

import com.yundasys.lab04springbootlocalmsg.dao.TOrderDao;
import com.yundasys.lab04springbootlocalmsg.entity.TOrder;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @PACKAGE_NAME: com.yundasys.lab04springbootlocalmsg.consumer
 * @NAME: ChangeOrderStatus
 * @USER: jiangta
 * @DATE: 2021/1/16
 * @TIME: 10:05 下午
 * @PROJECT_NAME: springboot-labs
 */
@Component("messageListener")
public class ChangeOrderStatus implements MessageListenerConcurrently {

    @Resource
    private TOrderDao tOrderDao;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list,
                                     ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        if(CollectionUtils.isEmpty(list)) return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;

        for(MessageExt ext: list) {
            String orderId = ext.getKeys();
            String msg = new String(ext.getBody());
            System.out.println("msg:" + msg);

            TOrder tOrder = tOrderDao.queryById(Integer.valueOf(orderId));
            if(tOrder == null) return ConsumeConcurrentlyStatus.RECONSUME_LATER;

            try {
                tOrder.setOrderStatus(1);
                tOrder.setUpdateTime(new Date());
                tOrder.setUpdateUser(0);
                tOrderDao.update(tOrder);
            }catch (Exception e) {
                e.printStackTrace();
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        }

        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
